<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="top-navbar">
			<view 
				class="nav-item" 
				:class="{ active: state.activeTab === 'tasklooby' }" 
				@click="switchTab('tasklooby')">
				任务大厅
			</view>
		</view>
		
		<!-- 内容区域 -->
		<view class="content">
			<!-- 任务大厅内容 -->
			<view v-if="!state.showTaskDetail" class="task-list">
				<view class="task-item" v-for="(task, index) in state.tasks" :key="task.id">
					<view class="task-header">
						<text class="task-id">任务编号：{{ task.id }}</text>
						<text class="task-status" :class="getStatusClass(task.status)">{{ getStatusText(task.status) }}</text>
					</view>
					
					<view class="task-content">
						<view class="task-info">
							<text class="task-title">{{ task.title }}</text>
						</view>
						
						<view class="task-details">
							<text class="customer-name">客户：{{ task.name }}</text>
							<text class="task-time">创建时间：{{ task.createTime }}</text>
							<text class="task-service">服务项目：{{ task.title }}</text>
							<text class="task-reward">报酬：¥{{ task.reward }}</text>
						</view>
						
						<view class="task-actions">
							<button class="action-btn" @click="viewTask(task)">查看详情</button>
							<button class="action-btn primary" @click="acceptTask(task)">接单</button>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 任务详情 -->
			<view v-if="state.showTaskDetail" class="task-detail">
				<view class="detail-header">
					<text class="back-btn" @click="closeTaskDetail">← 返回</text>
					<text class="detail-title">任务详情</text>
				</view>
				
				<view class="detail-content" v-if="state.selectedTask">
					<view class="task-header">
						<text class="task-id">任务编号：{{ state.selectedTask.id }}</text>
						<text class="task-status" :class="getStatusClass(state.selectedTask.status)">{{ getStatusText(state.selectedTask.status) }}</text>
					</view>
					
					<view class="task-section">
						<text class="section-title">任务信息</text>
						<view class="info-row">
							<text class="label">任务标题：</text>
							<text class="value">{{ state.selectedTask.title }}</text>
						</view>
						<view class="info-row">
							<text class="label">任务描述：</text>
							<text class="value">{{ state.selectedTask.des }}</text>
						</view>
						<view class="info-row">
							<text class="label">创建时间：</text>
							<text class="value">{{ state.selectedTask.createTime }}</text>
						</view>
						<view class="info-row">
							<text class="label">更新时间：</text>
							<text class="value">{{ state.selectedTask.updateTime }}</text>
						</view>
					</view>
					
					<view class="task-section">
						<text class="section-title">客户信息</text>
						<view class="info-row">
							<text class="label">客户姓名：</text>
							<text class="value">{{ state.selectedTask.name }}</text>
						</view>
						<view class="info-row">
							<text class="label">联系电话：</text>
							<text class="value phone">{{ state.selectedTask.phone }}</text>
						</view>
						<view class="info-row">
							<text class="label">服务地址：</text>
							<text class="value">{{ state.selectedTask.address }}</text>
						</view>
					</view>
					
					<view class="task-section" v-if="state.selectedTask.pic">
						<text class="section-title">相关图片</text>
						<image class="task-image" :src="state.selectedTask.pic" mode="widthFix"></image>
					</view>
					
					<view class="task-actions">
						<button class="action-btn" @click="closeTaskDetail">返回</button>
						<button v-if="state.selectedTask.status === 1" class="action-btn primary" @click="acceptTask(state.selectedTask)">接单</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { reactive, onMounted } from 'vue';
	import { getTaskList, grabOrder, getOrderDetail } from '../../api/tasklooby.js'
	
	export default {
		setup() {
			// 使用reactive创建响应式数据
			const state = reactive({
				activeTab: 'tasklooby', // 默认选中任务大厅
				tasks: [],
				pageNo: 1,
				pageSize: 10,
				selectedTask: null,
				showTaskDetail: false
			});
			
			// 切换顶部导航栏标签
			const switchTab = (tab) => {
				state.activeTab = tab;
			};
			
			// 加载任务列表
			const loadTasks = async () => {
				// 显示加载提示
				uni.showLoading({
					title: '加载中...'
				});
				
				try {
					const params = {
						pageNo: state.pageNo,
						pageSize: state.pageSize
					};
					
					const res = await getTaskList(params);
					console.log('获取任务列表返回数据:', res);
					
					// 根据后端实际返回的数据结构处理数据
					// 检查接口是否调用成功
					if (res && res.code === 0) {
						// 检查数据结构是否正确
						// 后端直接返回数组，而不是res.data.records结构
						if (res.data && Array.isArray(res.data)) {
							state.tasks = res.data;
							console.log('成功加载任务列表，数量:', state.tasks.length);
						} else {
							state.tasks = [];
							console.log('返回数据为空或不是数组');
						}
					} else {
						state.tasks = [];
						// 显示错误信息
						if (res) {
							console.log('接口返回错误信息:', res.msg);
							uni.showToast({
								title: res.msg || '获取任务列表失败',
								icon: 'none'
							});
						} else {
							console.log('接口调用失败，无返回数据');
							uni.showToast({
								title: '获取任务列表失败',
								icon: 'none'
							});
						}
					}
				} catch (error) {
					console.error('加载任务列表异常:', error);
					state.tasks = [];
					uni.showToast({
						title: '加载数据异常',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			};
			
			// 获取状态文本
			const getStatusText = (status) => {
				// 根据后端实际的状态值范围进行映射
				const statusMap = {
					1: '待抢接',
					2: '已抢接',
					3: '已完成',
					4: '已取消'
				};
				return statusMap[status] || '未知状态';
			};
			
			// 获取状态样式类
			const getStatusClass = (status) => {
				// 根据后端实际的状态值范围进行映射
				const classMap = {
					1: 'status-waiting',
					2: 'status-grabbed',
					3: 'status-completed',
					4: 'status-completed'
				};
				return classMap[status] || '';
			};
			
			// 查看任务详情
			const viewTask = async (task) => {
				try {
					uni.showLoading({
						title: '加载中...'
					});
					
					const res = await getOrderDetail(task.id);
					
					if (res && res.code === 0) {
						state.selectedTask = res.data;
						state.showTaskDetail = true;
					} else {
						uni.showToast({
							title: res.msg || '获取详情失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取任务详情异常:', error);
					uni.showToast({
						title: '数据加载异常',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			};
			
			// 关闭任务详情
			const closeTaskDetail = () => {
				state.showTaskDetail = false;
				state.selectedTask = null;
			};
			
			// 接单功能
			const acceptTask = (task) => {
				if (task.status !== 1) {
					const statusText = getStatusText(task.status);
					uni.showToast({
						title: `该任务${statusText}`,
						icon: 'none'
					});
					return;
				}
				
				// 调用确认抢单功能
				confirmGrabTask(task);
			};
			
			// 抢单功能
			const grabTask = (task) => {
				if (task.status !== 1) {
					const statusText = getStatusText(task.status);
					uni.showToast({
						title: `该任务${statusText}`,
						icon: 'none'
					});
					return;
				}
				
				uni.showModal({
					title: '抢单确认',
					content: `确定要抢接任务 "${task.title}" 吗？`,
					success: (res) => {
						if (res.confirm) {
							// 调用实际的抢单接口
							confirmGrabTask(task);
						}
					}
				});
			};
			
			// 确认抢单
			const confirmGrabTask = async (task) => {
				uni.showLoading({
					title: '抢单中...'
				});
				
				try {
					// 从本地存储获取用户信息
					const userInfo = uni.getStorageSync('userInfo');
					
					// 调用抢单接口
					const params = {
						id: task.id,
						userId: userInfo.id
					};
					
					const res = await grabOrder(params);
					
					// 检查后端返回结构
					if (res && typeof res === 'object') {
						if (res.code === 0) {
							// 抢单成功，跳转到待处理订单页面
							uni.showToast({
								title: '抢单成功！',
								icon: 'success'
							});
							
							// 将刚抢到的订单添加到本地存储，以便在订单页面显示
							const grabbedTask = {
								id: task.id,
								name: task.name,
								title: task.title,
								createTime: task.createTime,
								status: 1 // 待处理状态
							};
							
							// 存储到本地，供订单页面使用
							uni.setStorageSync('newlyGrabbedOrder', grabbedTask);
							
							// 延迟跳转到待处理订单页面
							setTimeout(() => {
								uni.switchTab({
									url: '/pages/order/order'
								});
							}, 1500);
						} else {
							// 抢单失败，显示后端错误信息
							const errorMsg = res.msg ? res.msg : '抢单失败，请稍后再试';
							uni.showToast({
								title: errorMsg,
								icon: 'none'
							});
							console.warn('抢单失败:', errorMsg);
						}
					} else {
						// 后端返回数据异常
						uni.showToast({
							title: '网络异常，请稍后再试',
							icon: 'none'
						});
						console.error('后端返回数据异常:', res);
					}
				} catch (error) {
					console.error('抢单异常:', error);
					uni.showToast({
						title: '抢单异常，请稍后重试',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			};
			
			// 页面加载时获取数据
			onMounted(() => {
				loadTasks();
			});
			
			return {
				state,
				switchTab,
				loadTasks,
				getStatusText,
				getStatusClass,
				viewTask,
				closeTaskDetail,
				acceptTask,
				grabTask,
				confirmGrabTask
			};
		}
	}
</script>

<style>
	.container {
		margin-top: calc(80rpx + var(--status-bar-height)); /* 为状态栏和导航栏留出空间 */
		padding: 0 20rpx;
		padding-bottom: calc(120rpx + env(safe-area-inset-bottom)); /* 为底部导航栏和安全区域留出空间 */
		padding-bottom: calc(120rpx + constant(safe-area-inset-bottom)); /* 兼容旧版iOS */
		min-height: 100vh;
		background-color: #f5f5f5;
		box-sizing: border-box;
		overflow-y: auto; /* 允许页面滚动 */
	}
	
	/* 顶部导航栏样式 */
	.top-navbar {
		display: flex;
		background-color: #fff;
		border-radius: 10rpx;
		margin: 20rpx 0;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		overflow: hidden;
	}
	
	.nav-item {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #666;
		padding: 20rpx 0;
	}
	
	.nav-item.active {
		color: #007AFF;
		border-bottom: 4rpx solid #007AFF;
	}
	
	.page-header {
		text-align: center;
		padding: 20rpx 0;
		margin-bottom: 20rpx;
		background-color: #fff;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}
	
	.page-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	
	.recommend-info {
		padding: 20rpx;
		background-color: #e8f4ff;
		text-align: center;
		margin-bottom: 20rpx;
		border-radius: 10rpx;
	}
	
	.info-text {
		font-size: 28rpx;
		color: #007AFF;
	}
	
	.task-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}
	
	.task-item {
		background-color: #fff;
		border-radius: 10rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}
	
	.task-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #eee;
	}
	
	.task-id {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
	}
	
	.task-status {
		font-size: 24rpx;
		padding: 5rpx 15rpx;
		border-radius: 30rpx;
	}
	
	.status-waiting {
		background-color: #cce5ff;
		color: #004085;
	}
	
	.status-grabbed {
		background-color: #fff3cd;
		color: #856404;
	}
	
	.status-completed {
		background-color: #d4edda;
		color: #155724;
	}
	
	.task-content {
		margin-bottom: 20rpx;
	}
	
	.task-info {
		margin-bottom: 20rpx;
	}
	
	.task-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 10rpx;
	}
	
	.task-desc {
		font-size: 28rpx;
		color: #666;
		display: block;
		margin-bottom: 20rpx;
	}
	
	.task-details {
		display: flex;
		flex-direction: column;
		gap: 10rpx;
	}
	
	.detail-item {
		display: flex;
	}
	
	.detail-label {
		font-size: 26rpx;
		color: #999;
		width: 120rpx;
	}
	
	.detail-value {
		font-size: 26rpx;
		color: #333;
		flex: 1;
	}
	
	.distance {
		color: #007AFF;
		font-weight: bold;
	}
	
	.price {
		color: #ff4d4f;
		font-weight: bold;
	}
	
	.reason {
		color: #ff6600;
		font-style: italic;
	}
	
	.task-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-top: 20rpx;
		border-top: 1rpx solid #eee;
	}
	
	.publish-time {
		font-size: 24rpx;
		color: #999;
	}
	
	.grab-btn {
		background-color: #007AFF;
		color: white;
		border: none;
		padding: 15rpx 30rpx;
		border-radius: 30rpx;
		font-size: 28rpx;
	}
	
	.grab-btn.disabled {
		background-color: #ccc;
	}
	
	.grab-btn:active {
		background-color: #0056cc;
	}
	
	.no-tasks {
		text-align: center;
		padding: 40rpx 0;
		background-color: #fff;
		border-radius: 10rpx;
	}
	
	.no-tasks-text {
		font-size: 28rpx;
		color: #999;
	}
	
	.task-detail {
		background-color: #fff;
		border-radius: 10rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}
	
	.detail-header {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #eee;
	}
	
	.back-btn {
		font-size: 28rpx;
		color: #007AFF;
	}
	
	.detail-title {
		flex: 1;
		text-align: center;
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	
	.task-section {
		margin-bottom: 30rpx;
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 20rpx;
		padding-bottom: 10rpx;
		border-bottom: 1rpx solid #eee;
	}
	
	.info-row {
		display: flex;
		margin-bottom: 15rpx;
	}
	
	.label {
		font-size: 28rpx;
		color: #999;
		width: 160rpx;
	}
	
	.value {
		font-size: 28rpx;
		color: #333;
		flex: 1;
	}
	
	.phone {
		color: #007AFF;
	}
	
	.task-image {
		width: 100%;
		border-radius: 10rpx;
		margin-top: 10rpx;
	}
</style>